# -*- coding:utf-8 -*-
# 爬虫：
# 目标网站：https://www.58pic.com/c/27075257
# 任务需求：1、抓取第一页前36张图片   2、使用bs4解析
# 存在一小点点问题


import requests
from bs4 import BeautifulSoup


class ImageWatermelon(object):
    def __init__(self):
        self.url = "https://www.58pic.com/c/27075257"
        self.number = 1
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }

    def get_data_index(self):
        response = requests.get(self.url, headers=self.headers)
        if response.status_code == 200:
            return response.text
        else:
            return None

    def parse_data(self, resp):
        soup = BeautifulSoup(resp, "lxml")
        data_list = soup.find_all("img", class_="lazy-bg-img")
        for data in data_list:
            title = data.get("alt") + str(self.number)
            image = "https:" + data.get("data-original")
            self.number += 1
            # 过滤不是要抓取的图片
            if image.split("_")[-1] != "webp":
                break
            self.save_data(title, image)

    def save_data(self, title, image):
        with open("./watermelon/" + title + ".jpg", "wb")as f:
            resp = requests.get(image).content
            f.write(resp)
            print(f"{title}:保存成功")

    def main(self):
        resp = self.get_data_index()
        self.parse_data(resp)


if __name__ == '__main__':
    src = ImageWatermelon()
    src.main()
